package cn.develop.server.service;

import cn.develop.server.commons.ResVO;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @author 1.
 * @version 1.0
 * @description: TODO 核心处理解析器
 * @date 2024/2/20 12:00
 */
@Service
public class AnalyzingService {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private RestTemplate restTemplate;


    /**
     * @param files 源文件列表
     * @description: 解析目标文件并调用分析服务接口
     * @return: ResVO - 结果封装类
     * @author 1.
     * @date: 2024/3/4 21:29
     */
    public ResVO parsedTargetFiles(MultipartFile[] files) throws IOException {
        List<Map<Object, Object>> analysisResSet = new ArrayList<>(3);
        for (MultipartFile file : files) {
            if (file.isEmpty()) continue;
            List<Object> dataSet = parsedHtmlFiles2Datas(file.getInputStream()); //解析得出数据集
            if (!dataSet.isEmpty()) {
                System.out.println(file.getName());
                System.out.println(file.getOriginalFilename());
                //TODO 调用分析服务接口分析数据并返回结果和所对应文件 key
                String targetUrl = "http://localhost:6000//evaluate-user-experience";
                ResponseEntity<Object> responseEntity = this.restTemplate.postForEntity(targetUrl, dataSet, Object.class);
                System.out.println(responseEntity.getBody());
                System.out.println(responseEntity.getHeaders());
                Map<Object, Object> map = new HashMap<>();
                map.put("fileName", file.getOriginalFilename());
                map.put("reportData", responseEntity.getBody());
                analysisResSet.add(map);
            }
        }
        return ResVO.ok(analysisResSet);
    }

    /**
     * @param ipts - 文件输入流
     * @return List
     * @description: 解析 .json 文件
     * @author 1.
     * @date: 2024/3/2 21:34
     */
    private List<Object> parsedJsonFiles2Datas(InputStream ipts) throws IOException {
        Map<String, Object> dataMap = objectMapper.readValue(ipts, Map.class);
        List<Object> data_list = (List<Object>) dataMap.get("data");
        return data_list;
    }

    /**
     * @param ipts - 文件输入流
     * @return List
     * @description: 解析.html文件
     * @author 1.
     * @date 2024/3/2 0:01
     */
    private List<Object> parsedHtmlFiles2Datas(InputStream ipts) throws IOException {
        // 解析文件
        Document doc = Jsoup.parse(ipts, null, "");
        // 获取json数据
        Elements p_s = doc.select("p");
        // 拼接得到的数据字符串
        StringBuilder sb = new StringBuilder();
        for (Element p : p_s) {
            sb.append(p.text());
        }
        String s = sb.toString();
            /*System.out.println(s);
            System.out.println("----------------------------------------------");*/
        // 替换掉错误的中文字符[“”]
        System.out.println(s = s.replaceAll("[”“]", "\""));

        // 将json字符串解析为JsonNode
        JsonNode jsonNodes = objectMapper.readTree(s);
            /*try {

            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }*/
        // 将jsonNode 转为 Map
        Map<String, Object> map = objectMapper.convertValue(jsonNodes, Map.class);
            /*System.out.println(map);
            map.forEach((String s1, Object o) -> System.out.println("key: " + s1 + " val: " + o));*/
        // 拿到关键的 data 数据
        List<Object> data_list = (List<Object>) map.get("data");
        System.out.println("-------------------------------------");
        data_list.forEach(System.out::println);
        return data_list;
    }
}
